<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\Coupon;
use app\model\Member;
use app\model\CouponReceive;

class CouponController extends Base
{

	function index()
	{
		$weid = weid();
		$page = input('post.page', 1, 'intval');
		$keyword = input('post.keyword', '', 'serach_in');
		$status = input('post.status', '', 'serach_in');
		$query = Coupon::where(['weid' => $weid]);
		if (!empty($keyword)) {
			$query->where('name', 'like', '%' . $keyword . '%');
		}

		if (!empty($status) || $status === "0") {
			$query->where(['status' => $status]);
		}

		$res = $query->order('sort asc,id desc')
			->paginate(getpage())
			->toArray();

		foreach ($res['data'] as &$vo) {
			if ($vo['coupon_type'] == 10) {
				$vo['couponway'] = '满：' . $vo['min_price'] . '元,减：' . $vo['reduce_price'] . '元';
			} elseif ($vo['coupon_type'] == 20) {
				$vo['couponway'] = '满：' . $vo['min_price'] . '元,打：' . $vo['discount'] . '折';
			}

			if ($vo['expire_type'] == 10) {

				if ($vo['expire_day'] > 0) {
					$vo['expire_day'] = $vo['expire_day'] . "天";
				} else {
					$vo['expire_day'] = "长期";
				}

				$vo['expire_type'] = '领取后：' . $vo['expire_day'] . '有效';;
			} elseif ($vo['expire_type'] == 20) {

				$vo['expire_type'] = '有效期：' . time_format($vo['start_time']) . '到' . time_format($vo['end_time']);
			}

			$vo['ptype'] = getCouponPtype($vo['ptype']);
			$vo['coupon_type'] = getCouponType($vo['coupon_type']);
			$vo['color'] = getColor($vo['color']);
			$vo['create_time'] = time_format($vo['create_time']);
			$vo['update_time'] = time_format($vo['update_time']);
		}

		$data['data'] = $res;
		return $this->json($data);
	}

	function listUpdate()
	{
		$data = only('id,is_recommand,status,sort');
		if (!$data['id']) throw new ValidateException('参数错误');
		Coupon::update($data);

		return $this->json(['msg' => '操作成功']);
	}

	public function update()
	{
		$id = $this->request->post('id');
		$data = input('post.');
		$data['update_time'] = time();

		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time']);

		if (empty($id)) {
			$data['weid'] = weid();
			$data['create_time'] = time();
			try {
				$res = Coupon::create($data);
				if ($res->id && empty($data['sort'])) {
					Coupon::update(['sort' => $res->id, 'id' => $res->id]);
				}
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '添加成功', 'data' => $res->id]);
		} else {

			try {
				Coupon::update($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '修改成功']);
		}
	}
	public function grant()
	{
		$id = $this->request->post('id');
		$user = input('post.user');
		if (empty($user)) {
			throw new ValidateException('请选择用户');
		}
		$Coupondata = Coupon::where(['weid' => weid(), 'id' => $id])->find()->toArray();
		$succeed = 0;
		$fail = 0;
		foreach ($user as $key => $vo) {
			$havecoupon = CouponReceive::where(['coupon_id' => $id, 'uid' => $vo])->find();

			if (empty($havecoupon)) {
				if (!empty($Coupondata)) {
					// $Coupondata = $Coupondata->toArray();
					//领取优惠券前，判断发放数量
					if ($Coupondata['total_num'] == -1 || $Coupondata['total_num'] > $Coupondata['receive_num']) {

						unset($Coupondata['id']);
						$Coupondata['uid'] = $vo;
						$Coupondata['coupon_id'] = $id;

						if ($Coupondata['expire_type'] == 10) {
							$Coupondata['end_time'] = strtotime("+" . $Coupondata['expire_day'] . " day");
						}

						$r = CouponReceive::create($Coupondata);

						if ($r) {
							$succeed++;
							//领取成功后更新优惠券领取数量
							$receive_num = $Coupondata['receive_num'] + 1;

							Coupon::update(['id' => $id, 'receive_num' => $receive_num]);
						} else {
							$fail++;
						}
					} else {
						$fail++;
					}
				}
			} else {
				$fail++;
			}
		}
		return $this->json(['msg' => '成功发放' . $succeed . '张，失败' . $fail . '张']);
	}
	//领取优惠券
	public function fetch()
	{
		$errno = 0;
		$message = '返回消息';
		$uid = UID();

		$id = input('post.id');

		$Coupondata = Coupon::where(['weid' => weid(), 'id' => $id])->find();
		$havecoupon = CouponReceive::where(['coupon_id' => $id, 'uid' => $uid])->find();

		if (empty($havecoupon)) {
			if (!empty($Coupondata)) {
				$Coupondata = $Coupondata->toArray();
				//领取优惠券前，判断发放数量
				if ($Coupondata['total_num'] == -1 || $Coupondata['total_num'] > $Coupondata['receive_num']) {

					unset($Coupondata['id']);
					$Coupondata['uid'] = UID();
					$Coupondata['coupon_id'] = $id;

					if ($Coupondata['expire_type'] == 10) {
						$Coupondata['end_time'] = strtotime("+" . $Coupondata['expire_day'] . " day");
					}

					$r = CouponReceive::create($Coupondata);

					if ($r) {
						$message = "领取成功";
						//领取成功后更新优惠券领取数量
						$receive_num = $Coupondata['receive_num'] + 1;

						Coupon::update(['id' => $id, 'receive_num' => $receive_num]);
					} else {
						$message = "领取失败";
					}
				} else {
					$errno = '2001';
					$message = '领取失败,你来晚了';
				}
			}
		} else {
			$errno = '2003';
			$message = '已经领取过了！';
		}
		return $this->json(['message' => $message, 'errno' => $errno, 'data' => $data]);
	}
	function getInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		$grant =  $this->request->post('grant', '', 'serach_in');
		$keyword = input('post.keyword', '', 'serach_in');
		if (!$id) throw new ValidateException('参数错误');
		$data = Coupon::field('*')->find($id)->toArray();

		if (empty($data['start_time'])) {
			$data['start_time'] = "";
		} else {
			$data['start_time'] = time_ymd($data['start_time']);
		}
		if (empty($data['end_time'])) {
			$data['end_time'] = "";
		} else {
			$data['end_time'] = time_ymd($data['end_time']);
		}
		$user = array();
		if ($grant == 1) {
			$query = Member::where(['weid' => weid()]);
			if (!empty($keyword)) {
				$query->where('id|nickname', 'like', '%' . $keyword . '%');
			}
			$res = $query->order('id desc')
				->paginate(getpage())
				->toArray();

			foreach ($res['data'] as $key => $vo) {
				$user[$key]['value'] = $vo['id'];
				$user[$key]['label'] = $vo['id'] . '-' . $vo['nickname'];
			}
		}
		return $this->json(['data' => $data, 'user' => $user]);
	}

	function delete()
	{
		$idx =  $this->request->post('id', '', 'serach_in');
		if (!$idx) throw new ValidateException('参数错误');
		Coupon::destroy(['id' => explode(',', $idx)], true);
		return $this->json(['msg' => '操作成功']);
	}
	function getField()
	{

		$data['colorarray'] = getColor();
		$data['ptypearray'] = getCouponPtype();
		$data['coupon_typearray'] = getCouponType();
		$data['expire_typearray'] = getExpireType();

		return $this->json(['data' => $data]);
	}
}
